using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;

using DotNetNuke;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;

namespace ACS.Modules.TapaTalk
{
    partial class TapatalkModuleSettings : TapatalkModuleBase
    {

        #region "Base Method Implementations"

        public override void LoadSettings()
        {
            try
            {

                if (!IsPostBack)
                {

                    BindModules();
                    if (Settings.forumModuleID != -1)
                    {
                        if ((drpModuleID.Items.FindByValue(Settings.forumModuleID.ToString()) != null))
                        {
                            drpModuleID.Items.FindByValue(Settings.forumModuleID.ToString()).Selected = true;
                        }
                        else
                        {
                            drpModuleID.SelectedIndex = 0;
                        }

                    }
                    else
                    {
                        drpModuleID.SelectedIndex = 0;
                    }
                    RefreshTapatalkLabels();
                    CheckInstallTapatalk(false, false);
                    this.chkIs_Open.Checked = Settings.Is_Open;
                    this.chkGuest_Access.Checked = Settings.Guest_Access;
                    this.chkDisable_search.Checked =Settings.Disable_Search;
                    this.chkDisable_latest.Checked = Settings.Disable_Latest;
                    this.chkDisable_pm.Checked = Settings.Disable_Pm;
             
                }
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        public override void UpdateSettings()
        {
            try
            {
                Settings.forumModuleID = Convert.ToInt32( drpModuleID.SelectedValue);
                Settings.forumTabID = Convert.ToInt32(ListBox1.Items.FindByValue(drpModuleID.SelectedValue).Text);
                Settings.Is_Open = this.chkIs_Open.Checked;
                Settings.Guest_Access = this.chkGuest_Access.Checked;
                Settings.Disable_Search = this.chkDisable_search.Checked;
                Settings.Disable_Latest = this.chkDisable_latest.Checked;
                Settings.Disable_Pm = this.chkDisable_pm.Checked;
                Settings.UpdateSettings();
                
            

            }

            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion
        #region "Event Methods"

        protected void BtnInstall_Click(object sender, EventArgs e)
        {
            try {
                if (IsTapatalkHandleInstaller())
                {
                    CheckInstallTapatalk(false, true);
                    DeleteKeys();
                }
                else
                {
                    CheckInstallTapatalk(true);
                    SaveChanges();
                }                
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        public void drpModuleID_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            RefreshTapatalkLabels();
        }


        #endregion
        #region "Private Methods"

        private void SaveChanges()
        {
            try
            {
                string path = (DotNetNuke.Common.Globals.ApplicationMapPath + "\\web.config");
                XmlDocument configFile = new XmlDocument();
                FileStream inStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                configFile.Load(inStream);
                //  system.web/httpHandlers <add verb="*" path="*mobiquo.php" type="ACS.Modules.TapaTalk.Service, ACS.Tapatalk.Service" />
                XmlNode node = configFile.SelectSingleNode("//configuration/system.web/httpHandlers");
                if (((node != null)))
                {
                    XmlNode newChild = node.SelectSingleNode("add[@path='*mobiquo.php']");
                    if ((newChild != null))
                    {
                        node.RemoveChild(newChild);
                    }
                    newChild = configFile.CreateElement("add");
                    node.AppendChild(newChild);
                    this.WriteSettingsToHttpHandlers("ACS.Modules.TapaTalk.Service, ACS.Tapatalk.Service", newChild, configFile, false);
                }
                // system.webserver/handlers     <add name="TapaTalkRequestHandler" path="*mobiquo.php" verb="*" type="ACS.Modules.TapaTalk.Service, ACS.Tapatalk.Service" preCondition="integratedMode" />

                XmlNode node2 = configFile.SelectSingleNode("//configuration/system.webServer/handlers");
                if (((node2 != null)))
                {
                    XmlNode node3 = node2.SelectSingleNode("add[@name='TapaTalkRequestHandler']");
                    if ((node3 != null))
                    {
                        node2.RemoveChild(node3);
                    }
                    node3 = configFile.CreateElement("add");
                    node2.AppendChild(node3);
                    this.WriteSettingsToHttpHandlers("ACS.Modules.TapaTalk.Service, ACS.Tapatalk.Service", node3, configFile, true);
                }



                inStream.Seek(0, SeekOrigin.Begin);
                inStream.SetLength(0);
                configFile.Save(inStream);
                inStream.Close();
                inStream.Dispose();
                configFile = null;
                //Module failed to load
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private void WriteSettingsToHttpHandlers(string httpModuleType, XmlNode mNode, XmlDocument configFile, bool iis7)
        {
            if (iis7)
            {
                this.SetAttribute("name", "TapaTalkRequestHandler", mNode, configFile);
            }

            this.SetAttribute("verb", "*", mNode, configFile);
            this.SetAttribute("path", "*mobiquo.php", mNode, configFile);
            this.SetAttribute("type", httpModuleType, mNode, configFile);
            if (iis7)
            {
                this.SetAttribute("preCondition", "integratedMode", mNode, configFile);
                //this.SetAttribute("resourceType", "Unspecified", mNode, configFile);
            }
        }
        private void DeleteKeys()
        {
            try
            {
                string path = (DotNetNuke.Common.Globals.ApplicationMapPath + "\\web.config");
                XmlDocument configFile = new XmlDocument();
                FileStream inStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                configFile.Load(inStream);
                XmlNode node = configFile.SelectSingleNode("//configuration/system.web/httpHandlers");
                if (((node != null)))
                {
                    XmlNode newChild = node.SelectSingleNode("add[@path='*mobiquo.php']");
                    if ((newChild != null))
                    {
                        node.RemoveChild(newChild);
                    }
                }
                XmlNode node2 = configFile.SelectSingleNode("//configuration/system.webServer/handlers");
                if (((node2 != null)))
                {
                    XmlNode node3 = node2.SelectSingleNode("add[@name='TapaTalkRequestHandler']");
                    if ((node3 != null))
                    {
                        node2.RemoveChild(node3);
                    }
                }

                inStream.Seek(0, SeekOrigin.Begin);
                inStream.SetLength(0);
                configFile.Save(inStream);
                inStream.Close();
                inStream.Dispose();
                configFile = null;
                //Module failed to load
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        private void SetAttribute(string name, string value, XmlNode node, XmlDocument configFile)
        {
            XmlAttribute attribute = node.Attributes[name];
            if ((attribute == null))
            {
                attribute = configFile.CreateAttribute(name);
                node.Attributes.Append(attribute);
            }
            attribute.Value = value;
        }
        private void CheckInstallTapatalk(bool Instalando = false, bool Desinstalando = false)
        {
            if ((Desinstalando) || (!Instalando && !IsTapatalkHandleInstaller()))
            {
                this.InstallMessage.Text = Localization.GetString("lblStatusKO.Text", this.LocalResourceFile);
                this.BtnInstall.Text = Localization.GetString("btnInstall.Text", this.LocalResourceFile);
            }
            else
            {
                this.BtnInstall.Text = Localization.GetString("btnUninstall.Text", this.LocalResourceFile);
                this.InstallMessage.Text = Localization.GetString("lblStatusOK.Text", this.LocalResourceFile);
            }
        }
        private bool IsTapatalkHandleInstaller()
        {
            bool instalado = true;
            string path = (DotNetNuke.Common.Globals.ApplicationMapPath + "\\web.config");
            XmlDocument configFile = new XmlDocument();
            FileStream inStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            configFile.Load(inStream);
            XmlNode node = configFile.SelectSingleNode("//configuration/system.web/httpHandlers");
            if (((node != null)))
            {
                XmlNode newChild = node.SelectSingleNode("add[@path='*mobiquo.php']");
                if ((newChild == null))
                {
                    instalado = false;
                }
            }
            XmlNode node2 = configFile.SelectSingleNode("//configuration/system.webServer/handlers");
            if (((node2 != null)))
            {
                XmlNode node3 = node2.SelectSingleNode("add[@name='TapaTalkRequestHandler']");
                if ((node3 == null))
                {
                    instalado = false;
                }
            }


            inStream.Close();
            inStream.Dispose();
            configFile = null;
            return instalado;
        }


        private void RefreshTapatalkLabels()
        {
            this.Tapatalk_ForumURL.Text = this.Context.Request.Url.Scheme + "://" + this.Context.Request.Url.Authority + this.Context.Request.ApplicationPath + ((this.Context.Request.ApplicationPath != "/")? "/":"") + this.TabModuleId ;
            if (this.drpModuleID.SelectedIndex!=0)
            {
                this.Tapatalk_EndPoint.Text =  this.drpModuleID.SelectedValue.ToString() ;
            }
            else
            {
                this.Tapatalk_EndPoint.Text = Localization.GetString("NotEndPoint",this.LocalResourceFile);
            }
        }
        private void BindModules()
        {
            DesktopModuleController objDesktopModuleController = new DesktopModuleController();
            DesktopModuleInfo objDesktopModuleInfo = objDesktopModuleController.GetDesktopModuleByModuleName("DNN_Forum");


            if ((objDesktopModuleInfo != null))
            {
                TabController objTabController = new TabController();
                ArrayList objTabs = objTabController.GetTabs(PortalId);
                foreach (DotNetNuke.Entities.Tabs.TabInfo objTab in objTabs)
                {
                    if ((objTab != null))
                    {
                        if ((objTab.IsDeleted == false))
                        {
                            ModuleController objModules = new ModuleController();
                            foreach (KeyValuePair<int, ModuleInfo> pair in objModules.GetTabModules(objTab.TabID))
                            {
                                ModuleInfo objModule = pair.Value;
                                if ((objModule.IsDeleted == false))
                                {
                                    if ((objModule.DesktopModuleID == objDesktopModuleInfo.DesktopModuleID))
                                    {
                                        if (PortalSecurity.IsInRoles(objModule.AuthorizedEditRoles) == true & objModule.IsDeleted == false)
                                        {
                                            string strPath = objTab.TabName;
                                            DotNetNuke.Entities.Tabs.TabInfo objTabSelected = objTab;
                                            while (objTabSelected.ParentId != Null.NullInteger)
                                            {
                                                objTabSelected = objTabController.GetTab(objTabSelected.ParentId, objTab.PortalID, false);
                                                if ((objTabSelected == null))
                                                {
                                                    break; // TODO: might not be correct. Was : Exit While
                                                }
                                                strPath = objTabSelected.TabName + " -> " + strPath;
                                            }

                                            ListItem objListItem = new ListItem();

                                            objListItem.Value = objModule.ModuleID.ToString();
                                            objListItem.Text = strPath + " -> " + objModule.ModuleTitle;

                                            drpModuleID.Items.Add(objListItem);
                                            ListItem AuxListItem = new ListItem();
                                            AuxListItem.Text = objTab.TabID.ToString();
                                            AuxListItem.Value = objModule.ModuleID.ToString();
                                            ListBox1.Items.Add(AuxListItem);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                drpModuleID.Items.Insert(0, new ListItem(Localization.GetString("SelectModule", this.LocalResourceFile), "-1"));
                ListBox1.Items.Insert(0, new ListItem("---", "-1"));
            }
        }

 
#endregion

  

    }

}

